import request from '@/services/request';

export const getAllNodes = () => {
    return request.get('/getAllNodes')
        .then(response => {
            const data = response.data;
            return data.data;
        })
        .catch(error => {
            throw new Error(error)
        });
};

export const getNodeRelation = () => {
    return request.get('/getAllNodeRelationships')
        .then(response => {
            const data = response.data;
            return data.data;
        })
        .catch(error => {
            throw new Error(error)
        });
};


export const getInitData = async () => {
    try {
        let links = await getNodeRelation();
        //         "source": 0,
        //         "target": 1,
        //         "relation": {
        //             "relationshipId":200,
        //             "relationship": "Belong_to",
        //             "created":123,
        //             "lineNumber":null,
        //             "isSelf": false
        //         }
        //     },{
        //         "source": 1,
        //         "target": 3,
        //         "relation": {
        //             "relationship": "need",
        //             "isSelf": false
        //         }
        //     },
        //     {
        //         "source": 2,
        //         "target": 6,
        //         "relation": {
        //             "relationship": "related_to",
        //             "isSelf": false
        //         }
        //     },{
        //         "id": 5,
        //         "type": "Belong_to",
        //         "startNodeName": "知识点1",
        //         "endNodeName": "章节1",
        //         "source": 6,
        //         "target": 0,
        //         "relation": {
        //             "relationship": "Belong_to",
        //             "isSelf": false
        //         }
        //     }
        // ];
        let nodes = await getAllNodes();
        return {
            links,
            nodes,
        };
    } catch (error) {
        throw new Error("获取数据失败");
    }
}

export const getDataBylabels = async (labels) => {
    let data = await getInitData();
    const filteredNodes = data.nodes.filter(node => labels.includes(node.label));
    const sortedNodes = filteredNodes.map((node, index) => ({
        ...node,
        id: index
    }));
    data.nodes = sortedNodes;


    const validLinks = data.links.map(link => {
        const startNode = data.nodes.find(node => node.name === link.startNodeName);
        const endNode = data.nodes.find(node => node.name === link.endNodeName);
        if (startNode && endNode) {
            return {
                ...link,
                source: startNode.id,
                target: endNode.id
            };
        }
        return null
    }).filter(link => link);
    data.links = validLinks;
    return data;
}